package com.digitalchina.frame.filter;

import java.io.IOException;
import java.util.Properties;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.digitalchina.frame.util.PropertiesUtils;


public class LoginFilter implements Filter{
	
	protected FilterConfig config = null;
    private String[] ignoreURL;
    protected String encoding = "";

    
	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
		this.encoding = config.getInitParameter("encoding");
		String u = config.getInitParameter("ignoreURL");
		if(u != null && !"".equals(u)){
			this.ignoreURL =  u.split(";");
			System.out.println("**************************");
			System.out.println("*****loginFilter init01***");
			System.out.println("**************************");
		}else{
			initIgnorePara();
			System.out.println("**************************");
			System.out.println("*****loginFilter init02***");
			System.out.println("**************************");
		}
		
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if(encoding != null && !"".equals(encoding)){
			request.setCharacterEncoding(encoding);
		}
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		HttpSession session = req.getSession();
		String url = req.getRequestURI();
		String method1 = req.getParameter("method");
		String method2 = req.getParameter("popup");
		if(method1 != null){
			url += "?method="+method1;
		}
		if(method2 != null){
			url += "?method="+method2;
		}
		Object obj = session.getAttribute("loginName");
		if(obj == null&&!isExsit(url)){
			resp.sendRedirect("/cfs/login.jsp"); 
		}else{
			chain.doFilter(request, response);
		}
		
	}
	
	@Override
	public void destroy() {
		this.config = null;
	    this.ignoreURL = null;
	    this.encoding = null;
	}
	
	public boolean isExsit(String url){
		boolean boo = false;
		/*int num = Arrays.binarySearch(ignoreURL,url);
		if(num < 0){
			boo = false;
		}*/
		for(String u : ignoreURL){
			if(u.trim().equals(url.trim())){
				boo = true;
				break;
			}
		}
		return boo;
	}
	
	private void initIgnorePara(){
		Properties properties = PropertiesUtils.getProperties("config-ignore.properties");
		Set<Object> set = properties.keySet();
		int length = set.size();
		ignoreURL = new String[length];
		int index = 0;
		for(Object obj : set){
			ignoreURL[index] = properties.getProperty((String)obj);
			index++;
		}
		
	}
	
}
